package com.example.fail5.link2arduino;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.xpf.ch340_library.CH340Master;
import com.xpf.ch340_library.driver.InitCH340;
import com.xpf.ch340_library.inteface.CallBack;
import com.xpf.ch340_library.inteface.CallBackUtils;
import com.xpf.ch340_library.utils.CH340Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class On2OneActivity extends AppCompatActivity implements InitCH340.IUsbPermissionListener, CallBack, View.OnTouchListener, OnClickListener {

    Button bt_top;
    Button bt_left;
    Button bt_right;
    Button bt_down;
    Button bt_clear;
    Button bt_save;
    lattice lattice;
    public boolean isOnLongClick = false;
    private static final String ACTION_USB_PERMISSION = "com.linc.USB_PERMISSION";
    private ScheduledExecutorService scheduledExecutor;
    Timer timer;
    TimerTask timerTask;
    int x = 0;
    private boolean isFirst;
    /**
     * 长按超过0.3秒，触发长按事件
     */
    private static final int LONGPRESSTIME = 150;
    /**
     * 判断是否进行点击
     */
    boolean isClick = true;

    boolean isFirstSend = true;
    boolean isContinuedtSend = false;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        CallBackUtils.setCallBack(this);
        initData();
        bt_top = findViewById(R.id.bt_top);
        bt_left = findViewById(R.id.bt_left);
        bt_right = findViewById(R.id.bt_right);
        bt_down = findViewById(R.id.bt_down);
        lattice = findViewById(R.id.lattice);
        bt_clear = findViewById(R.id.bt_clear);
        bt_save = findViewById(R.id.bt_save);


        bt_top.setOnTouchListener(this);
        bt_left.setOnTouchListener(this);
        bt_right.setOnTouchListener(this);
        bt_down.setOnTouchListener(this);
        bt_save.setOnClickListener(this);
        bt_clear.setOnClickListener(this);

        bt_clear.setText("sssssssssssss");
    }


    ExecutorService singleThreadExecutor;
    ExecutorService singleThreadExecutor2;

    private void updateAddOrSubtract(int viewId) {
        final int vid = viewId;

        singleThreadExecutor = Executors.newSingleThreadExecutor();

        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                sendData(json("z", 4));
//                myHandler.sendEmptyMessage(vid);

            }
        });


    }

    private void stopAddOrSubtract() {
        if (singleThreadExecutor != null) {
            singleThreadExecutor.shutdownNow();
            Log.d("On2OneActivity", "我停止了1");
            singleThreadExecutor = null;
        }
    }

    private void stopAddOrSubtract1() {
        if (scheduledExecutor != null) {
            scheduledExecutor.shutdownNow();
            Log.d("On2OneActivity", "我停止了1");
            scheduledExecutor = null;
        }
    }

    private void stopAddOrSubtract2() {
        if (singleThreadExecutor2 != null) {
            singleThreadExecutor2.shutdownNow();
            Log.d("On2OneActivity", "我停止了1");
            singleThreadExecutor2 = null;
        }
    }

    public String json(String str, int i) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("m", str);
            jsonObject.put("d", i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case R.id.bt_top:
                    sendData(json("z", 4));
//                    lattice.xChange2Y(false);
                    break;
                case R.id.bt_down:
//                    sendData(json("z", 4));
//                    lattice.xChange2Y(true);
                    break;
                case R.id.bt_left:
//                    sendData(json("z", 2));
//                    lattice.xChange2X(false);
                    break;
                case R.id.bt_right:
//                    sendData(json("z", 3));
                    lattice.xChange2X(true);
                    break;
                case 0x102:
                    String receive = bundle.getString("aa");
                    receive = receive.trim();
                    if (String.valueOf(x).equals(receive)) {
                        isContinuedtSend = true;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void sendData(String string) {
//        singleThreadExecutor = Executors.newSingleThreadExecutor();
//
//        singleThreadExecutor.execute(new Runnable() {
//            @Override
//            public void run() {

                if (isFirstSend) {
                    x = x + 1;
                    isFirstSend = false;
                    Log.d("On2OneActivity", "top");
                    Log.d("On2OneActivity", string+"+++");
                    byte[] bytes = CH340Util.toByteArray2(json("z", 1));
                    Log.d("On2OneActivity", "11111111" + isFirstSend);
                    CH340Util.writeData(bytes);

                } else if (isContinuedtSend) {
                    byte[] bytes = CH340Util.toByteArray2(json("z", 1));
                    isContinuedtSend = false;
                    Log.d("On2OneActivity", "222222" + isFirstSend);
                    CH340Util.writeData(bytes);
                }
//            }
//        });


    }

    private void initData() {
        InitCH340.setListener(this);
        if (!isFirst) {
            isFirst = true;
            // 初始化 ch340-library
            CH340Master.initialize(MyApplication.getContext());

        }
    }

    @Override
    public void result(boolean isGranted) {
        if (!isGranted) {
            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            InitCH340.getmUsbManager().requestPermission(InitCH340.getmUsbDevice(), mPermissionIntent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, usbFilter);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            Toast.makeText(On2OneActivity.this, "EXTRA_PERMISSION_GRANTED~", Toast.LENGTH_SHORT).show();
                            InitCH340.loadDriver(MyApplication.getContext(), InitCH340.getmUsbManager());
                        }
                    } else {
                        Toast.makeText(On2OneActivity.this, "EXTRA_PERMISSION_GRANTED null!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUsbReceiver);
        if (singleThreadExecutor2 != null) {
            stopAddOrSubtract2();
        }
    }

    @Override
    public void doSomeThing(String string) {
        Message message = new Message();
        message.what = 0x102;
        Bundle bundle = new Bundle();
        bundle.putString("aa", string);
        message.setData(bundle);
        myHandler.sendMessage(message);
    }

    @Override
    public boolean onTouch(final View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && event.getPointerCount() == 1) {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    isOnLongClick = true;
                    //长按逻辑触发，isClick置为false，手指移开后，不触发点击事件
                    isClick = false;

                    updateAddOrSubtract(v.getId());    //手指按下时触发不停的发送消息

                }
            };
            isClick = true;
            timer.schedule(timerTask, LONGPRESSTIME, 1000 * 60 * 60 * 24);
        } else if (event.getAction() == MotionEvent.ACTION_UP && event.getPointerCount() == 1) {

            if (isClick) {
                updateAddOrSubtract(v.getId());
            }
            isFirstSend = true;
            timerTask.cancel();
            timer.cancel();
            //取消计时
            stopAddOrSubtract();    //手指抬起时停止发送
            stopAddOrSubtract1();
        }
        return true;
    }


    @Override
    public void onClick(View v) {
        sendData(json("z", 2));
    }
}
